<#import "../tpl/pageTep.ftl" as page>
<@page.pageBase currentMenu="添加商品">
<style>
    .button-large {
        font-size: 16px;
    }

    .webuploader-pick {
        background: none;
        padding: 0;
    }
</style>
<div class="xm-product">
    <div class="row">
        <div class="panel">
            <div class="panel-header">
                <a href="${basepath}/rest/manage/product/toList">返回上一级</a>
            </div>
            <div class="panel-body">
                <form id="addForm" class="form-horizontal" action="${basepath}/rest/manage/product/insertAllJson"
                      method="post">
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品名称：
                        </label>

                        <div class="controls">
                            <input type="text" class="control-text span-width span10" name="name" placeholder="请输入商品名称"
                                   data-rules="{required : true}">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品类别：
                        </label>

                        <div class="controls">
                            <div id="p-catalog">
                                <input type="hidden" id="p-value" name="pCatalog" data-rules="{required : true}">

                                <input type="hidden" id="sub-value" name="catalogID" data-rules="{required:true}">
                            </div>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品宣传图：
                        </label>

                        <div class="controls">
                            <input type="text" class="input-normal control-text" name="adImage"
                                   data-rules="{required : true}" readonly>
                            <a id="proPicBtn" class="button button-min button-primary pull-right"
                               style="height:20px;margin-left: 10px;">上传</a>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品主图：
                        </label>

                        <div class="controls">
                            <input type="text" class="input-normal control-text" name="picture"
                                   data-rules="{required : true}" readonly>
                            <a id="pictureBtn" class="button button-min button-primary pull-right"
                               style="height:20px;margin-left: 10px;">上传</a>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">
                            <s>*</s>
                            商品详情：
                        </label>

                        <div class="controls control-row4" style="height: 350px;">
                            <textarea type="text" class="input-large" name="introduce" id="productHTML"
                                      data-rules="{required:true}"></textarea>
                        </div>
                    </div>
                    <h3 class="offset2">商品图片
                        <a class="button button-primary pull-right" id="imagesBtn" style="height:20px">新增图片</a>
                    </h3>
                    <hr>
                    <input type="hidden" class="control-text span-width " name="images" id="productImgs"
                           data-rules="{required:true}">

                    <div id="imagesGrid" class="xm-grid">
                    </div>
                    <div id="specList">
                        <h3 class="offset2">商品规格
                            <a class="button button-primary pull-right" href="javascript:addSpec()">新增规格</a>
                        </h3>
                        <hr>
                        <input type="hidden" class="input-normal control-text" name="specCombination"
                               data-rules="{required : true}"/>
                        <input type="hidden" class="input-normal control-text" name="specNowPrice"/>
                        <input type="hidden" class="input-normal control-text" name="specPurchasePrice"/>
                        <input type="hidden" class="input-normal control-text" name="specStock"/>

                        <div id="specGrid" class="xm-grid">
                        </div>
                    </div>
                    <div id="specList">
                        <h3 class="offset2">商品参数
                            <a class="button button-primary pull-right" href="javascript:addNature()">新增参数</a>
                        </h3>
                        <hr>
                        <input type="hidden" class="input-normal control-text" name="natureName"
                               data-rules="{required : true}"/>
                        <input type="hidden" class="input-normal control-text" name="natureValue"/>

                        <div id="natureGrid" class="xm-grid">
                        </div>
                    </div>
                    <div class="centered">
                        <button type="submit" class="button  button-large  button-success">立即上架</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<#-----------------------------------------------添加商品规格的弹出框------------------------------------------->
<div id="addSpecContent" style="display:none;">
    <form id="addSpecForm" class="form-horizontal">
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">规格组合：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="specCombination"
                           data-rules="{required : true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">售价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="specNowPrice"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">进价：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="specPurchasePrice"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">库存：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="specStock"
                           data-rules="{required : true,number:true}"/>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------添加商品规格的弹出框------------------------------------------->

<#-----------------------------------------------添加商品参数的弹出框------------------------------------------->
<div id="addNatureContent" style="display:none;">
    <form id="addNatureForm" class="form-horizontal">
        <div class="row">
            <div class="control-group span16">
                <label class="control-label">参数名称：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="natureName"
                           data-rules="{required : true}"/>
                </div>
            </div>
            <div class="control-group span16">
                <label class="control-label">规格参数：</label>

                <div class="controls">
                    <input type="text" class="input-normal control-text" id="natureValue"
                           data-rules="{required : true}"/>
                </div>
            </div>
        </div>
    </form>
</div>
<#-----------------------------------------------添加商品参数的弹出框------------------------------------------->


<script type="text/javascript">
    <#-----------------------------商品上架跳转----------------------------->
    var editor = UE.getEditor('productHTML');
    var Grid = BUI.Grid;
    var Store = BUI.Data.Store;
    var Data = BUI.Data;
    var Select = BUI.Select;
    var addForm = new BUI.Form.Form({
        srcNode: '#addForm',
        submitType: 'ajax',
        callback: function (data) {
            if (addForm.isValid()) {
                if (data.success) {
                    window.location.href = "${basepath}/rest/manage/product/toList";
                } else {
                    BUI.Message.Alert("上架失败", 'error');
                }
            } else {
                addForm.valid();
            }
        }
    }).render();

    //商品分类获取--获取商品分类名称
    var pStore = new Store({
        url: '${basepath}/rest/manage/catalog/getOneLevelCatalog',
        autoLoad: true,
        root: 'data'
    });
    var pSelect = new Select.Select({
        render: '#p-catalog',
        valueField: '#p-value',
        list: {
            itemTpl: '<li>{name}</li>',
            idField: 'id'
        },
        store: pStore
    }).render();

    //获取二级下拉数据源
    var subStore = new Store({
        url: '/rest/manage/catalog/getTwoLevelCatalog',  //设置加载数据的URL
        autoLoad: true, //创建Store时自动加载数据
        proxy: {
            method: 'GET',
            dataType: 'json'
        },
        root: 'data'
    });
    var subSelect = new Select.Select({
        render: '#p-catalog',
        valueField: '#sub-value',
        list: {
            itemTpl: '<li>{name}</li>',
            idField: 'id'
        },
        store: subStore
    }).render();
    pSelect.on('change', function (e) {
        var id = e.item.id;
        var obj = new Object();
        obj.pid = id;
        subStore.load(obj);       //接收对象参数
    });

    /*--------------------------产品图片列表  begin--------------------*/
    /**
     * 图片信息
     * @type {*[]}
     */
    var imagesColumns = [
        {
            title: '图片', dataIndex: 'url', elCls: "center", width: '30%', renderer: function (data) {
            return '<img src="${basepath}/' + data + '" width="100px" height="100px"/>'
        }
        },
        {
            title: '状态', dataIndex: 'state', elCls: "center", width: '30%', renderer: function (data) {
            if (data == "SUCCESS") {
                return "上传成功";
            }
            return "上传失败";
        }
        },
        {
            title: '操作', dataIndex: 'title', elCls: "center", width: '40%', renderer: function (data, obj, index) {
            return '<a href="javascript:delImages(' + index + ')">删除</a>';
        }
        }
    ];
    /**
     * 删除缓存图片信息
     * @param index
     */
    function delImages(index) {
        var record = imagesStore.findByIndex(index);
        imagesStore.remove(record);
        var imgs = imagesStore.getResult();
        var imgArr = new Array();
        for (var i = 0; i < imgs.length; i++) {
            imgArr[i] = imgs[i].url
        }
        $("#productImgs").val(imgArr.join(","));
    }
    var imagesStore = new Store({});
    var imagesGrid = new Grid.Grid({
        render: '#imagesGrid',
        width: '100%',//如果表格使用百分比，这个属性一定要设置
        columns: imagesColumns,
        idField: 'title',
        store: imagesStore
    });
    imagesGrid.render();
    /*--------------------------产品图片列表  end--------------------*/

    /*--------------------------产品规格列表  begin--------------------*/
    /**
     * 规格信息
     * @type {*[]}
     */
    var specColumns = [
        {title: '规格组合', dataIndex: 'specCombination', elCls: "center"},
        {title: '售价', dataIndex: 'specNowPrice', elCls: "center"},
        {title: '进价', dataIndex: 'specPurchasePrice', elCls: "center"},
        {title: '库存', dataIndex: 'specStock', elCls: "center"},
        {
            title: '操作', dataIndex: 'specCombination', elCls: "center", renderer: function (data) {
            return '<a href="javascript:delSpec(\'' + data + '\')">删除</a>';
        }
        }
    ];
    var specStore = new Store({});
    var specGrid = new Grid.Grid({
        render: '#specGrid',
        forceFit: true,
        columns: specColumns,
        store: specStore
    });
    specGrid.render();
    /**
     * 删除规格信息--不是放在数据库中，而是显示在列表上的用bui的remove实现
     * @param index
     */
    function delSpec(specCombination) {
        var record = specStore.find('specCombination', specCombination);
        specStore.remove(record);
    }
    /*--------------------------产品规格列表  end---------------------------*/

    /*--------------------------产品参数列表  begin--------------------*/
    /**
     * 参数信息
     * @type {*[]}
     */
    var natureColumns = [
        {title: '参数名称', dataIndex: 'natureName', elCls: "center"},
        {title: '参数值', dataIndex: 'natureValue', elCls: "center"},
        {
            title: '操作', dataIndex: 'natureName', elCls: "center", renderer: function (data) {
            return '<a href="javascript:delNature(\'' + data + '\')">删除</a>';
        }
        }
    ];
    var natureStore = new Store({});
    var natureGrid = new Grid.Grid({
        render: '#natureGrid',
        forceFit: true,
        columns: natureColumns,
        store: natureStore
    }).render();
    /**
     * 删除规格信息--不是放在数据库中，而是显示在列表上的用bui的remove实现
     * @param index
     */
    function delNature(name) {
        var record = natureStore.find('natureName', name);
        natureStore.remove(record);
    }
    /*--------------------------产品参数列表  end---------------------------*/

    /*------------------------图片上传插件配置  begin-----------------------*/
    //商品宣传图上传
    var proPictureUploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/common/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#proPicBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });
    //获取一张主图并传入url
    proPictureUploader.on('uploadSuccess', function (file, response) {
        proPictureUploader.removeFile(file);
        addForm.setFieldValue("adImage", response.url)
    });
    //商品主图上传
    var pictureUploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/common/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#pictureBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });
    //获取一张主图并传入url
    pictureUploader.on('uploadSuccess', function (file, response) {
        pictureUploader.removeFile(file);
        addForm.setFieldValue("picture", response.url)
    });

    //商品详情图片上传
    var uploader = WebUploader.create({
        auto: true,
        swf: '${staticpath}/common/ueditor/third-party/webuploader/Uploader.swf',
        server: '${basepath}/rest/manage/ued/config?action=uploadimage',
        pick: '#imagesBtn',
        resize: false,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png,'
        }
    });
    var imgs = imagesStore.getResult();
    uploader.on('uploadSuccess', function (file, response) {
        uploader.removeFile(file);
        if (imgs.length > 2) {
            BUI.Message.Alert('不能多于三张图片', function () {
            }, 'info');
        } else {
            imagesStore.add(response);
            var imgArr = new Array();
            for (var i = 0; i < imgs.length; i++) {
                imgArr[i] = imgs[i].url;
            }
            $("#productImgs").val(imgArr.join(","));
        }
    });
    /*------------------------图片上传插件配置  end-----------------------*/
    /*--------------------------添加商品规格方法 begin---------------------------------*/
    var specs = specStore.getResult();
    //新增商品规格--先存入表单中，不直接存入数据库
    function addSpecs() {
        var spec = {
            "specCombination": $('#specCombination').val(),
            "specNowPrice": $('#specNowPrice').val(),
            "specPurchasePrice": $('#specPurchasePrice').val(),
            "specStock": $('#specStock').val()
        };
        specStore.add(spec);
        var specCombinationArr = [],
                specNowPriceArr = [],
                specPurchasePriceArr = [],
                specStockArr = [];
        for (var i = 0; i < specs.length; i++) {
            specCombinationArr[i] = specs[i].specCombination;
            specNowPriceArr[i] = specs[i].specNowPrice;
            specPurchasePriceArr[i] = specs[i].specPurchasePrice;
            specStockArr[i] = specs[i].specStock;
        }
        $("input[name='specCombination']").val(specCombinationArr.join(";"));
        $("input[name='specNowPrice']").val(specNowPriceArr.join(";"));
        $("input[name='specPurchasePrice']").val(specPurchasePriceArr.join(";"));
        $("input[name='specStock']").val(specStockArr.join(";"));
    }
    /*--------------------------添加商品规格方法 end---------------------------------*/

    /*----------------------------------------------新增规格表单处理 begin------------------------------------*/
    var addSpecForm = new BUI.Form.Form({
        srcNode: '#addSpecForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            store.load(obj);
            addSpecForm.close();
        }
    }).render();
    var addSpecDialog = new BUI.Overlay.Dialog({
        title: '新增产品规格',
        width: 500,
        height: 300,
        contentId: 'addSpecContent',
        success: function () {
            if (addSpecForm.isValid()) {
                addSpecs();
                this.close();
            } else {
                addSpecForm.valid();
            }
        }
    });
    /**
     *规格新增按钮事件
     */
    function addSpec() {
        //新增规格的时候获取的表单为空
        $('#specCombination').val("");
        $('#specNowPrice').val("");
        $('#specPurchasePrice').val("");
        $('#specStock').val("");
        addSpecDialog.show();
    }
    /*----------------------------------------------新增规格表单处理 end------------------------------------*/

    /*--------------------------添加商品参数方法 begin---------------------------------*/
    var natures = natureStore.getResult();
    //新增商品规格--先存入表单中，不直接存入数据库
    function addNatures() {
        var nature = {
            "natureName": $('#natureName').val(),
            "natureValue": $('#natureValue').val()
        };
        natureStore.add(nature);
        var natureNameArr = [],
                natureValueArr = [];

        for (var i = 0; i < natures.length; i++) {
            natureNameArr[i] = natures[i].natureName;
            natureValueArr[i] = natures[i].natureValue;
        }
        $("input[name='natureName']").val(natureNameArr.join(";"));
        $("input[name='natureValue']").val(natureValueArr.join(";"));
    }
    /*--------------------------添加商品参数方法 end---------------------------------*/

    /*----------------------------------------------新增参数表单处理 begin------------------------------------*/
    var addNatureForm = new BUI.Form.Form({
        srcNode: '#addNatureForm',
        submitType: 'ajax',
        callback: function (data) {
            var obj = new Object();
            obj.start = 0; //返回第一页
            store.load(obj);
            addNatureForm.close();
        }
    }).render();
    var addNatureDialog = new BUI.Overlay.Dialog({
        title: '新增产品规格',
        width: 500,
        height: 200,
        contentId: 'addNatureContent',
        success: function () {
            if (addNatureForm.isValid()) {
                addNatures();
                this.close();
            } else {
                addNatureForm.valid();
            }
        }
    });
    /**
     *规格新增按钮事件
     */
    function addNature() {
        //新增规格的时候获取的表单为空
        $('#natureName').val("");
        $('#natureValue').val("");
        addNatureDialog.show();
    }
    /*----------------------------------------------新增参数表单处理 end------------------------------------*/

</script>

</@page.pageBase>